package com.thinksns.sociax.t4.android.presenter;

import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.thinksns.sociax.api.Api;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.android.data.StaticInApp;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.android.view.IWeiboDetailsView;
import com.thinksns.sociax.t4.model.ModelComment;
import com.thinksns.sociax.t4.model.ModelUser;
import com.thinksns.sociax.t4.model.ModelWeibo;
import com.thinksns.sociax.t4.unit.ButtonUtils;
import com.thinksns.sociax.thinksnsbase.bean.ListData;
import com.thinksns.sociax.thinksnsbase.exception.ApiException;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by hedong on 16/2/15.
 */
public class WeiboDetailsPresenter {
    private IWeiboDetailsView mWeiboDetailsView;
    private int weibo_id;

    public WeiboDetailsPresenter(IWeiboDetailsView detailsView) {
        this.mWeiboDetailsView = detailsView;
    }

    public void loadWeiboDetails(int weibo_id) {
        this.weibo_id = weibo_id;
        new getWeiboDetailTask().execute();
    }

    // 对微博点赞或取消赞 ,成功后才刷新界面
    public void postDigWeibo(final ModelWeibo weibo) {
        if (weibo == null) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                doDigWeibo(weibo);
            }
        }).start();

    }

    private void doDigWeibo(final ModelWeibo weibo) {
        int result = 0;
        try {
            result = executeDigWeibo(weibo);
        } catch (ApiException e) {
            System.err.println(e.toString());
        } catch (Exception e) {
            System.err.println(e.toString());
        }

        // result = 1 赞 or 取消赞成功
        mWeiboDetailsView.digWeiboUI(result);
        //sendBroad();


    }

    //发送广播更新UI
    public void sendBroad() {
//        Intent intent = new Intent(StaticInApp.NOTIFY_WEIBO);
//        ((ActivityWeiboDetail) mWeiboDetailsView).sendBroadcast(intent);
    }


    private int executeDigWeibo(final ModelWeibo weibo) throws ApiException, Exception {
        int result = 0;
        if (weibo.getIsDigg() == 1) {
            // 已经赞过
            result = new Api.StatusesApi().delDigg(weibo.getWeiboId());
        } else {
            // 还没有赞过
            result = new Api.StatusesApi().addDig(weibo.getWeiboId());
        }

        return result;
    }

    /**
     * 收藏微博
     *
     * @param weibo
     */
    public void postCollectWeibo(final ModelWeibo weibo) {
        try {
            new Api.StatusesApi().favWeibo(weibo,
                    new ApiHttpClient.HttpResponseListener() {

                        @Override
                        public void onSuccess(Object result) {
                            JSONObject json = (JSONObject) result;
                            int status = 0;
                            try {
                                status = json.getInt("status");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            mWeiboDetailsView.collectWeiboUI(status);
                        }

                        @Override
                        public void onError(Object result) {
                            mWeiboDetailsView.collectWeiboUI(-1);
                        }
                    });
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //同步改变微博的显示状态
        mWeiboDetailsView.toggleCollectStatus();

    }

    public void postCommentWeibo(final ModelWeibo weibo, final String content, final ModelComment replyComment) {
        if (ButtonUtils.isFastDoubleClick()) {
            return;
        }

        final long ctime = System.currentTimeMillis() / 1000;
        final ModelComment comment = createComment(content,replyComment);
        comment.setCtime(ctime + "");
        // mWeiboDetailsView.addCommentWeibo(comemnt);

        new Thread(new Runnable() {
            @Override
            public void run() {
                int status = 0;
                String msg = "";
                try {
                    Object result = new Api.StatusesApi().commentWeibo(comment.getContent(), weibo.getWeiboId(), comment.getReplyCommentId());
                    JSONObject jsonObject = new JSONObject(result.toString());
                    msg = jsonObject.optString("msg");
                    status = jsonObject.optInt("cid");
                    comment.setComment_id(status);
                    if (comment.getReplyCommentId() == 0) {
                        comment.setCommentType("weibo");
                    } else {
                        comment.setCommentType("comment");
                    }
                    /*回复评论不为空，且备注不为空，重新设置 content 内容*/
                    if (replyComment != null  && !TextUtils.isEmpty(replyComment.getRemark())){
                        comment.setContent("回复@" + replyComment.getRemark() + "：" + content);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (ApiException e) {
                    e.printStackTrace();
                }

                mWeiboDetailsView.commentWeiboUI(status, comment, msg);

            }
        }).start();
    }

    private ModelComment createComment(String content, ModelComment replyComment) {
        ModelComment comment = new ModelComment();
        comment.setType(ModelComment.Type.SENDING);      //设置评论处于发表状态
        comment.setUname(Thinksns.getMy().getUserName());
        comment.setUface(Thinksns.getMy().getUserface());
        comment.setUid(Thinksns.getMy().getUid() + "");
        comment.setUserApprove(Thinksns.getMy().getUserApprove());

        if (replyComment != null) {
            String newContent = "回复@" + replyComment.getUname() + "：" + content;
            comment.setContent(newContent);
            comment.setReplyCommentId(replyComment.getComment_id());
            comment.setTo_uid(Integer.parseInt(replyComment.getUid()));
        } else {
            comment.setContent(content);
        }

        return comment;
    }

    class getWeiboDetailTask extends AsyncTask<Void, Void, ModelWeibo> {

        @Override
        protected ModelWeibo doInBackground(Void... params) {
            try {
                return new Api.StatusesApi().getWeiboById(weibo_id);
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(ModelWeibo result) {
            if (result == null || result.equals("")) {
                mWeiboDetailsView.setErrorData("请求网络数据失败");
            } else if (result.isWeiboIsDelete() == 1) {
                mWeiboDetailsView.setErrorData("分享已删除");
            } else {
                //设置微博正文内容
                mWeiboDetailsView.setWeiboContent(result);
                //设置微博点赞用户列表
                mWeiboDetailsView.setDiggUsers(result.getDiggUsers());
                //设置微博评论列表
                mWeiboDetailsView.setWeiboComments(result.getCommentList());
            }
        }
    }
}
